package top.psjj.news.utils;

/**
 * @Auther:小陈的Java
 */

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * service层代理类，代理事务
 */
public class ServiceProxyFactory {
    public static Object getService(Class targetClass){
        return Proxy.newProxyInstance(targetClass.getClassLoader(), targetClass.getInterfaces(), new MyInvocationHandler(targetClass));
    }
    private static class MyInvocationHandler implements InvocationHandler {
        private Object target;
        public MyInvocationHandler(Class targetClass){
            try {
                this.target = targetClass.newInstance();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            //开启事物
            DataSourceUtils.startTransaction();
            Object result = null;
            try {
                //执行原来的代码
                result = method.invoke(target, args);
            } catch (Exception e) {
                e.printStackTrace();
                DataSourceUtils.rollback();
            }
            //提交事物
            DataSourceUtils.commit();
            return result;
        }
    }
}
